'''
Created on 2010/04/02

@author: enu
'''
import urllib
import uuid
import os
import random
from google.appengine.api import memcache
from oauth.exceptions import Unauthorized

class TemporaryTokenCredentials(object):
  
  def __init__(self):
    self._params = {}
  
  @classmethod
  def generate(cls):
    params = {
      'oauth_token': uuid.uuid4(),
      'oauth_token_secret':  os.urandom(32)
    }
    token = TemporaryTokenCredentials()
    token._params.update(params)
    return token
  
  def confirmCallbackURL(self, request):
    self._params['oauth_callback'] = request.params['oauth_callback']
    self._params['oauth_callback_confirmed'] = "true"  
  
  def save(self):
    memcache.add('TokenCredentials:%s' % self._params['oauth_token'], self._params, 500)

  @classmethod
  def load(cls, request):
    params = memcache.get('TokenCredentials:%s' % request.params['oauth_token'])
    token = TemporaryTokenCredentials()
    token._params.update(params)
    return token
  
  def generateVerificationCode(self):
    self._params['oauth_verifier'] = "%032x" % random.randint(1, 10 ** 10)
  
  def confirmVerificationCode(self, code):
    expected = self._params.get('oauth_verifier', None)
    if not expected or expected != code:
      raise Unauthorized('Invalid verification code')
    self._params['oauth_verifier_confirmed'] = "true"
  
  def respondTokenCredentials(self, wsgiResponse):
    query = dict(
      oauth_token =         self._params['oauth_token'],
      oauth_token_secret =  self._params['oauth_token_secret'] )
    if 'oauth_callback' in self._params:
      query['oauth_callback_confirmed'] = "true"
    wsgiResponse.out.write(urllib.urlencode(query))
  
  def callback(self, wsgiResponse):
    pass

class AuthorizedTokenCredentials(object):
  
  def __init__(self):
    pass
  
  @classmethod
  def exchange(cls, temporaryTokenCredentials):
    pass
  
  def save(self):
    pass
  
  def respondTokenCredentials(self, wsgiResponse):
    pass
